#include "EventLoopThread.h"
#include "EventLoop.h"
EventLoopThread::EventLoopThread(const ThreadInitCallback &cb,
                const string &name)
: _ownerLoop(nullptr)
, _exiting(false)
, _callback(cb)
, _name(name){}
EventLoopThread::~EventLoopThread()
{
    _exiting = true;
    if(_ownerLoop)
    {
        _ownerLoop->unloop();
    }
    if(_thread.joinable()) 
    {
        _thread.join();
    }
}
EventLoop *EventLoopThread::startLoop()
{
    _thread = thread(std::bind(&EventLoopThread::threadFunc, this));
    {
        std::unique_lock lock(_mutex);
        while(_ownerLoop == nullptr)
        {
            _cond.wait(lock);
        }
    }
    return _ownerLoop;
}

void EventLoopThread::threadFunc()
{
    EventLoop loop;
    {
        std::lock_guard lock(_mutex);
        _ownerLoop = &loop; // 设置所属EventLoop
        _cond.notify_all(); // 通知主线程
    }
    loop.setMainLoop(nullptr); // 设置主Reactor为nullptr
    if (_callback)
    {
        _callback(&loop); // 执行线程初始化回调
    }
    std::cout << "EventLoopThread " << _name << " started.\n";
    loop.loop(); // 进入事件循环

    std::lock_guard lock(_mutex);
    _ownerLoop = nullptr; // 线程退出时清空所属EventLoop
}